<?php
namespace app\common\service;



use app\common\model\SysSettingModel;
use GuzzleHttp\Exception\RequestException;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;


class MailSer
{
    /**
     * @var PHPMailer
     * */
    static $mailer = null;


    public static function instance()
    {
        if (empty(self::$mailer)) {
            self::$mailer = new PHPMailer(true);
        }
        return self::$mailer;
    }


    public static function send($rec_email, $body, array $input_data = [])
    {
        $mail_send_method = $input_data['send_method'] ?? 'sendHandle';
        $mailSer = new self();

        $mail_username = SysSettingModel::getContent('email', 'name');
        $mail_form = SysSettingModel::getContent('email', 'email');
        $mail_password = SysSettingModel::getContent('email', 'password');
        $mail_host = SysSettingModel::getContent('email', 'host');
        $mail_port = SysSettingModel::getContent('email', 'port');
//        dump($mail_username,$mail_form,$mail_password,$mail_host,$mail_port);
        $mail = $mailSer::instance();
        try {
            //Server settings
//            $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
            $mail->isSMTP();                                            //Send using SMTP
            $mail->Host = $mail_host;                     //Set the SMTP server to send through
            $mail->SMTPAuth = true;                                   //Enable SMTP authentication
            $mail->Username = $mail_form;                     //SMTP username
            $mail->Password = $mail_password;                               //SMTP password
            $mail->SMTPSecure = SysSettingModel::getContent('email', 'ssl');         //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
            $mail->Port = $mail_port;                                    //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

            //Recipients
            $mail->setFrom($mail_form, $mail_username);
            $rec_name = empty($input_data['rec_name']) ? $rec_email : $input_data['rec_name'];
            $mail->addAddress($rec_email, $rec_name);     //Add a recipient

            //Content
            $mail->isHTML(empty($input_data['is_html']));                                  //Set email format to HTML
            $mail->Subject = $input_data['subject'] ?? '项目需求';
            $mail->CharSet = "utf-8";
            $mail->AltBody = $input_data['alt_body'] ?? '请勿回复此邮件';
            $mailSer->$mail_send_method($mail, $body);
//            dump($mail);exit;
            $content = $mail->send();
        } catch (\Exception $e) {
            $content = $mail->ErrorInfo;
        }
        return $content;
    }

    //第三发发送邮件
    const URL = "http://email.szhulian.cn/api/email/send";
    public static function sendThird($rec_email, $body)
    {
        try {
            $client = new \GuzzleHttp\Client();
            $resp = $client->request('POST', self::URL, [
                'json' => [
                    'rec_mail'=>$rec_email,
                    'body'=>$body,
                    'host'=>request()->host(true),
                ],
                'verify'=>false,
                'headers' => [
                    'Accept' => 'application/json',
                ]
            ]);
            $content = $resp->getBody()->getContents();
        }catch (RequestException $e) {
            $content = $e->getResponse()->getBody()->getContents();

        } catch (\Exception $e) {
            // 进行错误处理
            $content = $e->getMessage();
        }
//        dump($content);exit;
        return $content ;
    }



    private function sendHandle(PHPMailer $mail, $body)
    {

//        dump($body);exit;

        preg_match_all('/<img src="([^"]+)"/', $body, $all_photo);
        $all_photo_imgs = $all_photo[1] ?? [];
        $img_arr = [];
        foreach ($all_photo_imgs as $key => $img) {
            $img_arr[$img] = 'cid:' . $key;
            $img_path = MakeImage::getImgPath($img, 'mailSer');
            $mail->addEmbeddedImage($img_path, $key);
        }
        $body = str_replace(array_keys($img_arr), array_values($img_arr), $body);


        $mail->Body = $body;
    }


}

